package org.rainwalk.bill.api.advice;

import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.rainwalk.bill.api.exception.BizException;
import org.rainwalk.bill.api.model.Response;
import org.rainwalk.bill.api.model.ResponseCode;
import org.rainwalk.bill.service.IMailService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.BindException;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.multipart.MaxUploadSizeExceededException;

@Slf4j
@RestControllerAdvice
public class JsonExceptionHandler {

    @Autowired(required = false)
    private IMailService mailService;

    @ExceptionHandler(Exception.class)
    public Response exceptionHandle(Exception e) {
        log.error("全局异常捕获：", e);
        if (mailService != null) {
            mailService.errorNotify(e);
        }
        return Response.error();
    }

    @ExceptionHandler(MethodArgumentNotValidException.class)
    public Response methodArgumentNotValidExceptionHandle(MethodArgumentNotValidException e) {
        ObjectError error = e.getBindingResult().getAllErrors().get(0);
        return Response.fail(ResponseCode.PARAMS_VERITY_FAIL, error.getDefaultMessage());
    }

    @ExceptionHandler(BindException.class)
    public Response bindExceptionHandle(BindException e) {
        ObjectError error = e.getBindingResult().getAllErrors().get(0);
        return Response.fail(ResponseCode.PARAMS_VERITY_FAIL, error.getDefaultMessage());
    }

    @ExceptionHandler(BizException.class)
    public Response bizExceptionHandle(BizException e) {
        return Response.fail(e.getResponseCode(), e.getMessage());
    }

    @ExceptionHandler(MaxUploadSizeExceededException.class)
    public Response maxUploadSizeExceededExceptionHandle(MaxUploadSizeExceededException e) {
        return Response.fail(ResponseCode.PARAMS_VERITY_FAIL, "请上传2MB以内的文件");
    }

}
